package nsu.edu.zsq.service.impl.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;
import nsu.edu.zsq.bean.SchRoom;
import nsu.edu.zsq.bean.SchRoomExample;
import nsu.edu.zsq.dao.SchRoomMapper;
import nsu.edu.zsq.exception.ParamException;
import nsu.edu.zsq.param.PageQuery;
import nsu.edu.zsq.service.sys.SchRoomService;
import nsu.edu.zsq.service.sys.SysLogService;
import nsu.edu.zsq.util.BeanValidator;
import nsu.edu.zsq.util.ExcelUtil;

/** 
* Description: 学校教室的service实现类<br>
*/
@Slf4j
@Service
public class SchRoomServiceImpl implements SchRoomService {
    
    /**
     * 课程节数
     */
    private final String[] COURSE_TIME = {"12", "34", "56", "78", "910"};
    
    @Autowired
    private SchRoomMapper schRoomMapper;
    @Autowired
    private SysLogService sysLogService;

    @Override
    public SchRoom getSchRoom(int roomId) {
        SchRoom schRoom = schRoomMapper.selectByPrimaryKey(roomId);
        return schRoom;
    }
    
    @Override
    public List<String> listBuildName() {
        List<String> listBuildName = schRoomMapper.listBuildName();
        return listBuildName;
    }

    @Override
    public PageInfo<SchRoom> listSchRoomWithPageByBuildName(String buildName, PageQuery pageQuery) {
        // 所有教室
        String allSchRoom = "0";
        PageHelper.startPage(pageQuery.getPageNum(),pageQuery.getPageSize());
        SchRoomExample example = new SchRoomExample();
        List<SchRoom> listSchRoom = null;
        if (allSchRoom.equals(buildName)) {
            // 获取所有教室
            listSchRoom = schRoomMapper.selectDistinctByExample(example);
        } else {
            example.createCriteria().andBuildNameEqualTo(buildName);
            listSchRoom = schRoomMapper.selectDistinctByExample(example);
        }
        PageInfo<SchRoom> pageInfo = new PageInfo<SchRoom>(listSchRoom, pageQuery.getNavigatePages());
        return pageInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importSchRoomFromExcel(MultipartFile excelFile) {
        List<SchRoom> listSchRoom = ExcelUtil.importExcel(excelFile, 1, 1, SchRoom.class);
        saveBatchSchRoom(listSchRoom);
        log.info("导入学校教室数据一共【{}】条",listSchRoom.size());
    }
    
    @Override
    public void exportSchRoomToExcel(HttpServletResponse response) {
        SchRoomExample example = new SchRoomExample();
        List<SchRoom> listSchRoom = schRoomMapper.selectDistinctByExample(example);
        ExcelUtil.exportExcel(listSchRoom,"教室列表","Sheet1",SchRoom.class,"学校教室.xlsx",response);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBatchSchRoom(List<SchRoom> listSchRoom) {
        List<Map<String, String>> after = new ArrayList<Map<String, String>>();
        for (SchRoom schRoom : listSchRoom) {
            // 自定义日志内容
            Map<String, String> map = new HashMap<String, String>();
            map.put("buildName", schRoom.getBuildName());
            map.put("roomNuber", schRoom.getRoomNumber());
            after.add(map);
            /**
             * 每周五天，每天五节课（12，34，56，78，910），即每个教室共有25个使用时段
             * 所有这里每条教室保存25条数据，方便以后查空闲的教室
             */
            // 教室名称
            StringBuilder roomName = new StringBuilder();
            roomName.append(schRoom.getBuildName());
            roomName.append("-");
            roomName.append(schRoom.getRoomNumber());
            schRoom.setRoomName(roomName.toString());
            if (checkRoomNameExist(schRoom.getRoomName())) {
                throw new ParamException("存在相同的教室名称");
            }
            for (int i = 1; i < 6; i++) {
                for (int j = 0; j < 5; j++) {
                    // 上课节
                    schRoom.setCourseTime(COURSE_TIME[j]);
                    // 上课周
                    schRoom.setCourseWeek(String.valueOf(i));
                    // 保存
                    schRoomMapper.insertSelective(schRoom);
                }
            }
        }
		/*
		 * // 添加日志 String instruction = "教室管理-导入";
		 * sysLogService.saveSysLogBySysUser(null, after, instruction);
		 */
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSchRoom(SchRoom schRoom) {
        BeanValidator.check(schRoom);
        SchRoom after = new SchRoom();
        BeanUtils.copyProperties(schRoom, after);
        // 教室名称
        StringBuilder roomName = new StringBuilder();
        roomName.append(schRoom.getBuildName());
        roomName.append("-");
        roomName.append(schRoom.getRoomNumber());
        schRoom.setRoomName(roomName.toString());
        if (checkRoomNameExist(schRoom.getRoomName())) {
            throw new ParamException("存在相同的教室名称");
        }
        for (int i = 1; i < 6; i++) {
            for (int j = 0; j < 5; j++) {
                // 上课节
                schRoom.setCourseTime(COURSE_TIME[j]);
                // 上课周
                schRoom.setCourseWeek(String.valueOf(i));
                // 保存
                schRoomMapper.insertSelective(schRoom);
            }
        }
        
		/*
		 * // 添加日志 String instruction = "教室管理-添加教室";
		 * sysLogService.saveSysLogBySysUser(null, after, instruction);
		 */
    }
    
    /**
     * 通过教室名称检查该教室是否存在
     * @param roomName 教室名称
     * @return boolean true：存在 false：不存在
     */
    private boolean checkRoomNameExist(String roomName) {
        SchRoomExample example = new SchRoomExample();
        example.createCriteria().andRoomNameEqualTo(roomName);
        return schRoomMapper.countByExample(example) > 0;
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateSchRoom(SchRoom schRoom) {
        BeanValidator.check(schRoom);
        SchRoom after = new SchRoom();
        BeanUtils.copyProperties(schRoom, after);
        after.setRoomId(null);
        // 教室名称
        StringBuilder roomName = new StringBuilder();
        roomName.append(schRoom.getBuildName());
        roomName.append("-");
        roomName.append(schRoom.getRoomNumber());
        schRoom.setRoomName(roomName.toString());
        if (checkRoomNameExist(schRoom.getRoomName())) {
            throw new ParamException("存在相同的教室名称");
        }
        SchRoom oldSchRoom = getSchRoom(schRoom.getRoomId());
        // roomId不更新
        schRoom.setRoomId(null);
        // 根据roomName进行更新（即更新全部的25条记录）
        SchRoomExample example = new SchRoomExample();
        example.createCriteria().andRoomNameEqualTo(oldSchRoom.getRoomName());
        schRoomMapper.updateByExampleSelective(schRoom, example);
        
		/*
		 * // 自定义日志内容 Map<String, String> before = new HashMap<String, String>(2);
		 * before.put("buildName", oldSchRoom.getBuildName()); before.put("roomNumber",
		 * oldSchRoom.getRoomNumber());
		 */
		/*
		 * // 添加日志 String instruction = "教室管理-编辑教室";
		 * sysLogService.saveSysLogBySysUser(before, after, instruction);
		 */
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBatchSchRoom(int[] roomIds) {
        List<SchRoom> before = new ArrayList<SchRoom>();
        for (int roomId : roomIds) {
            SchRoom schRoom = getSchRoom(roomId);
            before.add(schRoom);
            SchRoomExample example = new SchRoomExample();
            example.createCriteria().andRoomNameEqualTo(schRoom.getRoomName());
            schRoomMapper.deleteByExample(example);
        }

		/*
		 * // 添加日志 String instruction = "教室管理-批量删除";
		 * sysLogService.saveSysLogBySysUser(before, null, instruction);
		 */
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteSchRoom(int roomId) {
        SchRoom before = getSchRoom(roomId);
        // 删除25个教室
        SchRoomExample example = new SchRoomExample();
        example.createCriteria().andRoomNameEqualTo(before.getRoomName());
        schRoomMapper.deleteByExample(example);
        
		/*
		 * // 添加日志 String instruction = "教室管理-单个删除";
		 * sysLogService.saveSysLogBySysUser(before, null, instruction);
		 */
    }

    
}
